package me.helllp.book.netty.step06;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{

	private byte[] req = "$_TIME".getBytes();
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		ctx.write(Unpooled.copiedBuffer("netty rocks! ", CharsetUtil.UTF_8));
		ByteBuf buf = null;
		for(int i=0; i<100; i++){
			buf = Unpooled.buffer(req.length);
			buf.writeBytes(req);
			ctx.writeAndFlush(buf);
		}
//		ctx.writeAndFlush(Unpooled.copiedBuffer("netty rocks! ", CharsetUtil.UTF_8));
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
		System.out.println("Client received: " + ByteBufUtil.hexDump(buf.readBytes(buf.readableBytes())));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
